package admin.models;

import helpers.GeneralHelper;
import helpers.StringHelper;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.Article;
import entities.Category;

public class CategoryModel {
	
	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "category_";

	private static CategoryModel instance = null;
	
	public static CategoryModel getInstance() {
		if (instance == null) {
			instance = new CategoryModel();
		}
		
		return instance;
	}
	
	private CategoryModel() {
		try {
			ObjectifyService.register(Category.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}

		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}

	public ArrayList<Category> list(int limit, int page) {
		ArrayList<Category> categories = new ArrayList<Category>();

		int start = (page - 1) * limit;
		Query<Category> q = ofy.query(Category.class).limit(limit)
				.offset(start);
		for (Category category : q) {
			categories.add(category);
		}

		return categories;
	}

	public ArrayList<Category> getAll() {
		ArrayList<Category> categories = new ArrayList<Category>();

		Query<Category> q = ofy.query(Category.class);
		for (Category category : q) {
			categories.add(category);
		}

		return categories;
	}

	public void insert(Category category) {
		ofy.put(category);
	}

	public void delete(Category category) {
		try {
			cache.remove(prefix + category.getAlias());
		} catch (Exception e) {
			// TODO: handle exception
		}

		ofy.delete(category);
	}

	public Category getCategory(String id) {
		Category category = new Category();
		try {
			category = ofy.get(new Key<Category>(Category.class, id));
		} catch (Exception e) {
			category = null;
		}
		return category;
	}

	public Category getCategoryByAlias(String alias) {
		Category category = new Category();
		if (cache != null && cache.containsKey(prefix + alias)) {
			category = (Category) cache.get(prefix + alias);
		} else {
			try {
				category = ofy.query(Category.class).filter("alias", alias).get();
				cache.put(prefix + alias, category);
			} catch (Exception e) {
				category = null;
			}
		}
		return category;
	}
	
	public boolean checkAliasExists(String alias) {
		boolean isExists = false;
		
		Category category = getCategoryByAlias(alias);
		
		if (category != null) {
			isExists = true;
		}
		
		return isExists;
	}
}
